const fs = require('fs')
const { parse } = require("csv-parse");
const csv = require('csvtojson')
const axios = require('axios')


/**
 * config start =======================================
 */


/**
 * config end =======================================
 */



let metricTmp = {
    name: "node_sys_service_info",
    type: "gauge",
    metricsLabels: [
        {
            labelName: "provinceCode",
            labelValue: "451"
        },
        {
            labelName: "nodeId",
            labelValue: ""
        },
        {
            labelName: "serviceCode",
            labelValue: "NCS"
        },
        {
            labelName: "serviceName",
            labelValue: "号卡数据管理系统"
        },
        {
            labelName: "subServiceCode",
            labelValue: "NCS-NumberSegmentSet"
        },
        {
            labelName: "subServiceName",
            labelValue: "号段配置管理"
        },
        {
            labelName: "version",
            labelValue: "1.1.0"
        },
        {
            labelName: "subVersion",
            labelValue: "1.1.0"
        },
        {
            labelName: "publishTime",
            labelValue: "202212231000"
        },
        {
            labelName: "state",
            labelValue: "running"
        },
        {
            labelName: "type",
            labelValue: "H5"
        }
    ],
    value: 1
};

async function readDataFromCsv(filePath) {
    return csv().fromFile(filePath)
        .subscribe(json => {
            return new Promise((resolve, reject) => {
                if (!json) {
                    reject('read csv error')
                } else {
                    resolve(json)
                }
            })
        })
}

let serviceInfoMetricArray = new Array();

async function sendMetrics_serverInfo(nodeId, provinceCode, year, month, day, hourMinute) {


    serviceList.filter(m => m.parent_id != 0).forEach(m1 => {
        let parent = serviceList.filter(m2 => m2.id == m1.parent_id);
        let subService = subServiceList.filter(m2 => m2.en_svc_id == parent[0].id);
        let serviceVersion = serviceVersionList.filter(m2 => m2.code == m1.code);

        let metricTmpCopy = JSON.parse(JSON.stringify(metricTmp))
        metricTmpCopy.metricsLabels.forEach(m3 => {
            if (m3.labelName == 'provinceCode') {
                m3.labelValue = provinceCode;
            } else if (m3.labelName == 'nodeId') {
                m3.labelValue = nodeId;
            } else if (m3.labelName == 'serviceCode') {
                m3.labelValue = parent[0].code;
            } else if (m3.labelName == 'serviceName') {
                m3.labelValue = parent[0].name;
            } else if (m3.labelName == 'subServiceCode') {
                m3.labelValue = m1.code;
            } else if (m3.labelName == 'subServiceName') {
                m3.labelValue = m1.name;
            } else if (m3.labelName == 'version') {
                m3.labelValue = serviceVersion[0].version;
            } else if (m3.labelName == 'subVersion') {
                m3.labelValue = subService[0].en_svc_ver_name;
            } else if (m3.labelName == 'publishTime') {
                m3.labelValue = serverServicePublishTime;
            } else if (m3.labelName == 'type') {
                m3.labelValue = m1.note;
            }

        })
        serviceInfoMetricArray.push(metricTmpCopy)
    })
    let jsonTmp = JSON.stringify(serviceInfoMetricArray)
}

let nodeList ;
let serviceList ;
let serviceVersionList ;
let subServiceList;

let totalCount = 0;

async function batchSendMetrics(year, month, day, hourMinutes) {



    nodeList.filter(x => {
        if (!nodeId || nodeId === '') {
            return true;
        } else {
            return nodeId == x.code;
        }
    }).forEach(nodeInfo => {
        let provinceList = nodeInfo.province.split(',');
        provinceList.filter(x => {
            if (!provinceCode || provinceCode == "") {
                return true;
            } else {
                return x == provinceCode;
            }
        }).forEach( async p => {
            await sendMetrics_serverInfo(nodeInfo.code, p, year, month, day, hourMinutes);
        })

    })

    let jsonTmp = JSON.stringify(serviceInfoMetricArray)

    // fs.writeFile("msisdnWriteResouce.txt", jsonTmp, error => {
    //     if (error) throw error;
    // })
    

    let reportTime = year + month + day + hourMinutes + '00';
    customConfig = {
        headers: {
            'Content-Type': 'application/json',
            'reportTime': reportTime
        }
    };
    totalCount += serviceInfoMetricArray.length;
    console.log(reportTime + " metrics count: " + serviceInfoMetricArray.length + ", totalCount: " + totalCount)
    serviceInfoMetricArray = new Array();
    const resp = await axios.post(REQ_URL, jsonTmp, customConfig);
    // console.log('resp data: ', resp.data)
}

const serverServicePublishTime = "20221010091030"
// 填写具体的端节点ID，为空字符串时代表所有端节点ID
const nodeId = "";
// 填写具体的省份编码，为空字符串代表所有的省份
const provinceCode = "";
const REQ_URL = 'http://15.116.20.124:30061/metrics/report';
// const REQ_URL = 'http://localhost:8080/metrics/report';


function sleep(time) {
    return new Promise((resolve, reject) => {
        return setTimeout(resolve, time);
    });
}

async function batchSendMetricsLoop() {
    nodeList = await readDataFromCsv(__dirname + '/./en_endnode.csv');
    serviceList = await readDataFromCsv(__dirname +'/./en_endnode_svc.csv');
    serviceVersionList = await readDataFromCsv(__dirname +'/./en_endnode_svc_ver.csv');
    subServiceList = await readDataFromCsv(__dirname +'/./en_endnode_sub_svc.csv');

    let hourMinutesList = [
        '0000', '0030', '0100', '0130', '0200',
        '0230', '0300', '0330', '0400', '0430',
        '0500', '0530', '0600', '0630', '0700',
        '0730', '0800', '0830', '0900', '0930',
        '1000', '1030', '1100', '1130', '1200',
        '1230', '1300', '1330', '1400', '1430',
        '1500', '1530', '1600', '1630', '1700',
        '1730', '1800', '1830', '1900', '1930',
        '2000', '2030', '2100', '2130', '2200',
        '2230', '2300', '2330'
      ]
    let days = [31,28,31,30,31,30,31,31,30,31,30,31] 

    let year = 2023;
    ourter:
    for (let i = 1; i <= 12; i++ ) {
        let month = i.toString().padStart(2, '0');
        reportMonth = month;
        let day = days[i - 1];
        for (let j = 1; j <= day; j++) {
            let dayStr = j.toString().padStart(2, '0');
            reportDay = dayStr;
            for (let m = 0; m < hourMinutesList.length; m++) {
                let hourMinute = hourMinutesList[m]
                await batchSendMetrics( year, month, dayStr, hourMinute);
                // break ourter;
            }
            // break ourter;
        }
        // break ourter;
    }
    reportMonth = '';
    reportDay = '';
}

// batchSendMetricsLoop();

let reportMonth = '';
let reportDay = '';

async function execReport() {
    if (reportMonth === '' && reportDay === '') {
        batchSendMetricsLoop();
        return 'start...'
    } else {
        return 'server info: ' + reportMonth + ", " + reportDay;
    }
}

exports.execReport = execReport;